package org.lee.jfc.line;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * LineChartDemo
 * 折线图（带两个系列）保存到png图片
 *
 * @author dralee
 * @date 2021-12-29 14:49:39
 **/
public class LineChartDemo3 {

    private JFreeChart createChart(XYDataset dataset) {
        JFreeChart chart = ChartFactory.createXYLineChart("Average salary per age",
                "Age", "Salary (€)", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        XYPlot plot = chart.getXYPlot();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesPaint(0, Color.RED);
        renderer.setSeriesStroke(0, new BasicStroke(2.0f));
        renderer.setSeriesPaint(1, Color.BLUE);
        renderer.setSeriesStroke(1, new BasicStroke(2.0f));

        plot.setRenderer(renderer);
        plot.setBackgroundPaint(Color.white);
        plot.setRangeGridlinesVisible(false);
        plot.setDomainGridlinesVisible(false);

        chart.getLegend().setFrame(BlockBorder.NONE);
        chart.setTitle(new TextTitle("Average Salary per Age", new Font("Serif", Font.BOLD, 18)));
        return chart;
    }

    private XYDataset createDataset() {
        XYSeries series1 = new XYSeries("2020");
        series1.add(18, 530);
        series1.add(20, 581);
        series1.add(25, 860);
        series1.add(30, 901);
        series1.add(38, 1298);
        series1.add(52, 2201);

        XYSeries series2 = new XYSeries("2021");
        series2.add(18, 567);
        series2.add(20, 612);
        series2.add(25, 800);
        series2.add(30, 981);
        series2.add(38, 1502);
        series2.add(52, 2320);

        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series1);
        dataset.addSeries(series2);
        return dataset;
    }

    private void saveAsPng(String fileName) throws IOException {
        XYDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        ChartUtils.saveChartAsPNG(new File(fileName), chart, 450, 400);
    }

    public static void main(String[] args) throws IOException {
        new LineChartDemo3().saveAsPng("line_chart.png");
    }
}
